package web;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import system.MTO;
import system.RunTimeData;
import system.StaticData;
import system.bean.ClientCode;
import system.bean.Message;
import system.bean.MessageType;
import system.bean.UserState;
import biz.interfaces.IUserBiz;
import biz.interfaces.IUserLoginLogBiz;
import biz.util.YwsOLUtil;
import entity.User;
import entity.UserLoginLog;

/***
 * 全局请求控制器
 * 
 * @author lcy
 * 
 */
public class RequestManagerController extends AbstractControllerUtil implements Controller {

	private IUserBiz iUserBiz = null;
	private IUserLoginLogBiz iUserLoginLogBiz = null;

	private HttpServletRequest request = null;
	private HttpSession session = null;

	

	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		if (!validateRequest(request))
			return null;

		this.request = request;
		this.session = request.getSession();
		// this.response = response;

		String action = request.getParameter("action");

		if ("login".equals(action)) // 登录
			return doLogin();
		if ("logout".equals(action)) // 注销
			return doLogout();
		if ("changeheart".equals(action)) // 修改心情
			return doChangeheart();
		if ("addfriend".equals(action)) // 添加好友
			return doAddfriend();
		if ("deletefriend".equals(action)) // 删除好友
			return doDeletefriend();
		if ("changefriendmemo".equals(action)) // 修改好友备注
			return doChangefriendmemo();
		if ("addtoblacklist".equals(action)) // 拉黑
			return doAddtoblacklist();
		if ("chat".equals(action)) // 聊天
			return doChat();
		return null;

	}

	private ModelAndView doLogin() throws IOException {
		Map<String, Object> model = new HashMap<String, Object>();
		// 移除session

		session.removeAttribute(StaticData.SESSION_USERID_NAME);

		User user = new User();
		user.setYwsLoginName(request.getParameter("ywsloginname"));
		user.setYwsPassWord(request.getParameter("password"));
		MTO mto = iUserBiz.UserLogin(user);
		model.put("clientcode", mto.getClientCode().ordinal());

		// 如果登录成功，则设置session
		if (mto.getClientCode() == ClientCode.LOGIN_SUCCESS) {
			@SuppressWarnings("unchecked")
			Map<String, Object> data = (Map<String, Object>) mto
					.getDataObject();

			// 登录成功，在session存储userid和登录ip（w为了防止session欺骗）
			session.setAttribute(StaticData.SESSION_USERID_NAME,
					data.get("userid"));
			session.setAttribute(StaticData.SESSION_LOGIN_IP_NAME,
					request.getRemoteAddr());
			session.setAttribute(StaticData.SESSION_LOGIN_FORWARDIP_NAME,
					request.getHeader("x-forwarded-for"));

			for (String key : data.keySet())
				model.put(key, data.get(key));

			// model.put("groups", data.get("groups"));
			// model.put(key, value);
			// model.put(key, value);
		}

		// 登录日志
		if (StaticData.SYSYTEM_LOGIN_LOG)
			addUserLoginLog(mto);

		return new ModelAndView("jsonView", model);
	}

	private ModelAndView doLogout() throws IOException {
		return null;
	}

	private ModelAndView doAddtoblacklist() throws IOException {
		return null;
	}

	private ModelAndView doChat() throws IOException {

			Integer targetUid = Integer.valueOf(request.getParameter("targetuserid"));
			UserState targetState = RunTimeData.Get(targetUid);
			
			Message m = new Message();
			m.setMessageContent(request.getParameter("chatcontent"));

			m.setMessageType(MessageType.ChatContent);
			m.setSenderID(session.getAttribute(StaticData.SESSION_USERID_NAME).toString());
			m.setSendTime(YwsOLUtil.GetNowTime());
			m.setTargetID(targetUid.toString());
			LinkedHashSet<Message> hisMessageList = targetState.getMessagelist();

			hisMessageList.add(m);
			return null;
		
	}

	private ModelAndView doDeletefriend() throws IOException {
		return null;
	}

	private ModelAndView doChangefriendmemo() throws IOException {
		return null;
	}

	private ModelAndView doAddfriend() throws IOException {
		return null;
	}

	private ModelAndView doChangeheart() throws IOException {
		return null;
	}

	private void addUserLoginLog(MTO mto) {

		String remoteIP = request.getRemoteAddr(); // 远程IP，可能是代理IP
		String forwardIP = request.getHeader("x-forwarded-for"); // 真实IP
		if (!YwsOLUtil.IsIP(forwardIP))
			forwardIP = null;

		UserLoginLog userLoginLog = new UserLoginLog();

		userLoginLog.setLoginName(request.getParameter("ywsloginname"));
		userLoginLog.setLoginPassword(request.getParameter("password"));
		userLoginLog.setRemoteIP(remoteIP);
		userLoginLog.setLoginSuccess(mto.isSuccess());
		userLoginLog.setLoginTime(YwsOLUtil.GetNowTime());
		userLoginLog.setForwardIP(forwardIP);
		userLoginLog.setAdmin(false);
		userLoginLog.setDenied(false);
		iUserLoginLogBiz.AddUserLoginLog(userLoginLog);
	}

	public void setiUserBiz(IUserBiz iUserBiz) {
		this.iUserBiz = iUserBiz;
	}

	public void setiUserLoginLogBiz(IUserLoginLogBiz iUserLoginLogBiz) {
		this.iUserLoginLogBiz = iUserLoginLogBiz;
	}


}
